package org.cogaen.java2d.xml;

import java.awt.Image;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.cogaen.core.Core;
import org.cogaen.java2d.ImageUtil;
import org.cogaen.logging.LoggingService;
import org.cogaen.resource.ResourceManager;

public class ImageXmlHandle extends XmlHandle {

	private static final String LOGGING_SOURCE = ResourceManager.LOGGING_SOURCE;
	private ImageParser imageParser;
	
	public ImageXmlHandle(String resourceName, String filename) {
		super(resourceName, filename, ImageParser.createFilter(resourceName));
		this.imageParser = new ImageParser();
	}

	@Override
	protected Object parseXml(Core core, XMLStreamReader reader) throws XMLStreamException {
		try {
			this.imageParser.parse(reader);
			return createImage(core);				
		} catch (ParseException e) {
			LoggingService logger = LoggingService.getInstance(core);
			logger.logWarning(LOGGING_SOURCE, "unable to load image '" + getName() + "': " + e.getMessage());
			return ImageUtil.createDummyImage(core);
		}
	}

	private Image createImage(Core core) {
		if (this.imageParser.getImageSrc() == null) {
			LoggingService logger = LoggingService.getInstance(core);
			logger.logWarning(LOGGING_SOURCE, "no image source specified for '" + getName() + "'");
			return ImageUtil.createDummyImage(core);
		}
		
		URL url = ResourceManager.getInstance(core).getUrl(this.imageParser.getImageSrc());
		
		if (url == null) {
			LoggingService logger = LoggingService.getInstance(core);
			logger.logWarning(LOGGING_SOURCE, "unable to locate image resource '" + this.imageParser.getImageSrc() + "'");
			return ImageUtil.createDummyImage(core);
		} else {
			try {
				return ImageUtil.makeCompatibleImage(core, ImageIO.read(url));
			} catch (IOException e) {
				LoggingService logger = LoggingService.getInstance(core);
				logger.logWarning(LOGGING_SOURCE, "unable to load image '" + this.imageParser.getImageSrc() + "'");
				return ImageUtil.createDummyImage(core);
			}
		}
	}

}
